<script>
  import RightToolBar from "@/components/common/right-toolbar";

  export default {
    layout: 'admin',
    name: 'admin-store',
    components: {
      RightToolBar,
    },
    data() {
      return {
        // 客户端初始化
        clientInit: true,
        // 商店列表
        storeList: [],
        // 选中商店列表
        storeSelection: [],
        // 商店总数
        totalNum: 0,
        // 经营大类枚举列表
        mainClassList: [],
        // 状态枚举列表
        statusEnumList: [],
        // 商店检索表单显示状态[true-显示 false-隐藏]
        searchFormVisible: true,
        // 商店检索表单对象
        searchForm: {
          // 商店名称
          word: '',
          // 经营大类
          mainClass: '',
          // 经营小类
          subClass: '',
          // 状态
          status: '',
          // 当前展示页码
          page: 1,
          // 当前页显示个数
          limit: 10
        },
        // 数据加载状态[false-不加载 true-加载]
        dataLoad: false,
        // 按钮禁用状态[true-禁用 false-可用]
        buttonLoad: false,
      }
    },
    computed: {
      // 经营小类枚举列表
      subClassList() {
        if (!this.searchForm.mainClass && this.searchForm.mainClass !== 0) {
          return [];
        }
        let mainClassEnum = this.mainClassList.find(mainClassEnum => mainClassEnum.value === this.searchForm.mainClass);
        if (!mainClassEnum) {
          return [];
        }
        return mainClassEnum.children;
      }
    },
    filters: {
      /**
       * 经营大类名称映射
       * @param {number} value         经营大类值
       * @param {Array}  mainClassList 经营大类枚举列表
       * @return {string} 经营大类名称
       */
      mainClassFormat(value, mainClassList) {
        for (let mainClassEnum of mainClassList) {
          if (mainClassEnum.value === value) {
            return mainClassEnum.name;
          }
        }
        return '';
      },
      /**
       * 经营小类名称映射
       * @param {number} value         经营小类值
       * @param {number} mainClass     经营大类值
       * @param {Array}  mainClassList 经营大类枚举列表
       * @return {string} 经营大类名称
       */
      subClassFormat(value, mainClass, mainClassList) {
        let subClassList = [];
        for (let mainClassEnum of mainClassList) {
          if (mainClassEnum.value === mainClass) {
            subClassList = mainClassEnum.children;
            break;
          }
        }
        for (let subClassEnum of subClassList) {
          if (subClassEnum.value === value) {
            return subClassEnum.name;
          }
        }
        return '';
      },
      /**
       * 商店状态名称映射
       * @param {number} value          商店状态值
       * @param {Array}  statusEnumList 商店状态枚举列表
       */
      statusFormat(value, statusEnumList) {
        for (let statusEnum of statusEnumList) {
          if (statusEnum.value === value) {
            return statusEnum.name;
          }
        }
        return '';
      }
    },
    async asyncData({ app, params, error }) {
      // 客户端调用直接返回
      if (process.client) return {};
      let searchForm = {
        word: '',
        mainClass: '',
        subClass: '',
        status: '',
        page: 1,
        limit: 10
      }
      if (params.searchForm) {
        searchForm = JSON.parse(params.searchForm);
      }
      let res;
      try {
        res = await app.$axios.$post('/store/page/list', searchForm);
      } catch (e) {
        error(e.msg || '网络异常，请求失败');
        return {};
      }
      const data = res.data;

      try {
        res = await app.$axios.$get('/store/enums');
      } catch (e) {
        error(e.msg || '网络异常，请求失败');
        return {};
      }
      const enumData = res.data;

      return {
        clientInit: false,
        storeList: data.data,
        totalNum: data.totalNum,
        mainClassList: enumData.mainClassList,
        statusEnumList: enumData.statusEnumList,
        searchForm: searchForm
      }
    },
    created() {
      if (process.client) {
        if (this.clientInit) {
          const params = this.$route.params;
          if (params.searchForm) {
            this.searchForm = JSON.parse(params.searchForm);
          }
          // 客户端加载
          this.getStoreList();
          // 枚举加载
          this.getStoreEnums();
        }
      }
    },
    methods: {
      /**
       * 分页获取商店方法
       */
      getStoreList() {
        // 开始加载
        this.dataLoad = true;
        this.$axios.$post('/store/page/list', this.searchForm)
            .then(({ data }) => {
              this.storeList = data.data;
              this.totalNum = data.totalNum;
            })
            .catch(() => {})
            .finally(() => {
              // 结束加载
              this.dataLoad = false;
            });
      },
      /**
       * 获取商店枚举数据
       */
      getStoreEnums() {
        this.$axios.$get('/store/enums')
          .then(({ data }) => {
            this.mainClassList = data.mainClassList;
            this.statusEnumList = data.statusEnumList;
          })
          .catch(() => {});
      },
      /**
       * 商店检索事件
       */
      searchHandle() {
        this.searchForm.page = 1;

        this.getStoreList();
      },
      /**
       * 重置检索表单事件
       */
      resetFormHandle() {
        // 重置表单
        this.$refs.searchForm.resetFields();

        this.searchForm.page = 1;
      },
      /**
       * 选中经营大类事件
       */
      changeMainClassHandle() {
        // 清理选中的经营小类
        this.searchForm.subClass = '';
      },
      /**
       * 商店查看跳转事件
       * @param {string} id 商店主键
       */
      toViewStoreHandle(id) {
        this.$router.push({ name: 'admin-store-detail',
          params: { id: id, prePageSearchForm: JSON.stringify(this.searchForm) }
        });
      },
      /**
       * 商店添加跳转事件
       * @param {string} id 商店主键
       */
      toAddStorePageHandle(id) {
        this.$router.push({ name: 'admin-store-add',
          params: { id: id, prePageSearchForm: JSON.stringify(this.searchForm) }
        });
      },
      /**
       * 商店修改跳转事件
       * @param {string} id 商店主键
       */
      toModifyStorePageHandle(id) {
        this.$router.push({ name: 'admin-store-modify',
          params: { id: id, prePageSearchForm: JSON.stringify(this.searchForm) }
        });
      },
      /**
       * 提交商店事件
       * @param {string} id 商店主键
       */
      submitStoreHandle(id) {
        this.buttonLoad = true;
        this.$axios.$post('/store/fast/submit', null, { params: { id }})
          .then(({data}) => {
            if (data) {
              this.notify('warning', '提交失败', data);
              return
            }
            this.notify('success', '提示', '商店提交操作成功');
            // 重新加载数据
            this.getStoreList();
          })
          .catch(() => {})
          .finally(() => {
            this.buttonLoad = false;
          })
      },
      /**
       * 商店撤销审核事件
       * @param {string} id 商店主键
       */
      withdrawAuditStoreHandle(id) {
        this.$confirm('您确定要商店撤销审核吗，是否继续？', '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'danger'
        })
        .then(() => {
          this.buttonLoad = true;
          return this.$axios.$post('/store/withdraw/audit', null, { params: { id }})
        })
        .then(() => {
          this.notify('success', '提示', '商店撤销审核操作成功');
          // 重新加载数据
          this.getStoreList();
        })
        .catch(err => {
          if (err.code === 409) {
            // 重新加载数据
            this.getStoreList();
          }
        })
        .finally(() => {
          this.buttonLoad = false;
        })
      },
      /**
       * 删除商店事件
       * @param {Object} store 商店对象
       */
      deleteStoreHandle(store) {
        this.$confirm('您确定要删除商店吗，是否继续？', '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'danger'
        })
        .then(() => {
          let storeIdList = [];
          if (store) {
            storeIdList.push(store.id);
          } else {
            storeIdList = this.storeSelection.map(store => store.id);
          }
          // 按钮禁用
          this.buttonLoad = true;
          return this.$axios.$delete('/store/delete', { data: storeIdList })
        })
        .then(() => {
          this.notify('success', '操作成功', '商店删除成功');
          // 刷新表格
          this.getStoreList();
        })
        .catch(() => {})
        .finally(() => {
          // 按钮恢复可用
          this.buttonLoad = false;
        })
      },
      /**
       * 每页显示个数变化事件
       * @param {number} size 最新显示个数值
       */
      sizeChangeHandle(size) {
        let searchForm = this.searchForm;
        searchForm.page = 1;
        searchForm.limit = size;
        this.getStoreList();
      },
      /**
       * '点击特定页码'、'上一页'、'下一页'操作事件
       * @param {number} index 最新页码
       */
      currentChangeHandle(index) {
        let searchForm = this.searchForm;
        if (searchForm.page === index) {
          return;
        }
        searchForm.page = index;
        this.getStoreList();
      },
      /**
       * 查看商店事件
       * @param store 商店对象
       */
      viewStoreHandle(store) {
        if (store.status !== 50) {
          return;
        }
        this.$router.push({ name: 'admin-store-detail',
          params: { id: store.id, prePageSearchForm: JSON.stringify(this.searchForm) }
        });
      }
    }
  }
</script>

<template>
  <div class="store-page">
    <transition name="el-zoom-in-top">
      <el-form v-show="searchFormVisible" inline size="mini" :model="searchForm" ref="searchForm"
               @keyup.enter.native="searchHandle">
        <el-form-item prop="word" label="商店检索">
          <el-input v-model="searchForm.word" clearable placeholder="请输入商店名称"></el-input>
        </el-form-item>
        <el-form-item prop="mainClass">
          <el-select v-model="searchForm.mainClass" clearable placeholder="请选择经营大类" @change="changeMainClassHandle">
            <el-option v-for="mainClassEnum in mainClassList" :key="'mainClass' + mainClassEnum.value"
                       :label="mainClassEnum.name" :value="mainClassEnum.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="subClass">
          <el-select v-model="searchForm.subClass" clearable placeholder="请选择经营小类">
            <el-option v-for="subClassEnum in subClassList" :key="'subClass' + subClassEnum.value"
                       :label="subClassEnum.name" :value="subClassEnum.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="status">
          <el-select v-model="searchForm.status" clearable placeholder="请选择状态">
            <el-option v-for="statusEnum in statusEnumList" :key="'status' + statusEnum.value"
                       :label="statusEnum.name" :value="statusEnum.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="dataLoad" @click="searchHandle" type="primary" icon="el-icon-search">查询</el-button>
          <el-button :disabled="dataLoad" @click="resetFormHandle" plain icon="el-icon-refresh-right">重置</el-button>
        </el-form-item>
      </el-form>
    </transition>
    <div class="s-tool">
      <el-button :disabled="dataLoad" @click="toAddStorePageHandle(undefined)"
                 type="primary" size="mini" plain icon="el-icon-plus">添加</el-button>

      <el-button :disabled="storeSelection.length === 0 || dataLoad || buttonLoad" @click="deleteStoreHandle"
                 type="danger" size="mini" plain icon="el-icon-delete">删除</el-button>

      <right-tool-bar :search-visible="searchFormVisible" :search-load="dataLoad"
                      @toggle-search="searchFormVisible = !searchFormVisible" @refresh-table="getStoreList" />
    </div>
    <el-table
        v-loading="dataLoad"
        element-loading-text="商店列表加载中..."
        element-loading-spinner="el-icon-loading"
        :data="storeList"
        @selection-change="(val) => this.storeSelection = val"
        ref="storeTable"
    >
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column prop="name" header-align="center" align="center" label="商店名称">
        <template v-slot="{row}">
          <span @click="viewStoreHandle(row)" :class="{'store-name': row.status === 50}">{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="mainClass" header-align="center" align="center" label="经营大类">
        <template v-slot="{row}">
          {{ row.mainClass | mainClassFormat(mainClassList) }}
        </template>
      </el-table-column>
      <el-table-column prop="subClass" header-align="center" align="center" label="经营小类">
        <template v-slot="{row}">
          {{ row.subClass | subClassFormat(row.mainClass, mainClassList) }}
        </template>
      </el-table-column>
      <el-table-column prop="area" header-align="center" align="center" label="面积"></el-table-column>
      <el-table-column prop="status" header-align="center" align="center" label="状态">
        <template v-slot="{row}">
          {{ row.status | statusFormat(statusEnumList)}}
        </template>
      </el-table-column>
      <el-table-column prop="accountName" header-align="center" align="center" label="账户名称"></el-table-column>
      <el-table-column prop="accountStatus" header-align="center" align="center" label="账户状态">
        <template v-slot="{row}">
          {{ row.accountStatus === 0 ? '正常' : '停用' }}
        </template>
      </el-table-column>
      <el-table-column prop="bossName" header-align="center" align="center" label="老板名称"></el-table-column>
      <el-table-column prop="bossStatus" header-align="center" align="center" label="老板状态">
        <template v-slot="{row}">
          {{ row.bossStatus === 0 ? '正常' : '停用' }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" header-align="center" align="center" label="创建时间"></el-table-column>
      <el-table-column
        header-align="left"
        width="180"
        label="操作">
        <template v-slot="{ row }">
          <el-button v-if="row.status === 50" type="text" icon="el-icon-view"
                     @click="toViewStoreHandle(row.id)">
            查看
          </el-button>
          <el-button v-if="row.status === 0" type="text" :disabled="buttonLoad" icon="el-icon-switch-button"
                     @click="submitStoreHandle(row.id)">
            提交
          </el-button>
          <el-button v-if="row.status === 0 || row.status === 20" type="text" icon="el-icon-edit"
                     @click="toAddStorePageHandle(row.id)">
            编辑
          </el-button>
          <el-button v-if="row.status === 40 || row.status === 50" type="text" icon="el-icon-edit"
                     @click="toModifyStorePageHandle(row.id)">
            修改
          </el-button>
          <el-button v-if="row.status === 10" type="text" :disabled="buttonLoad" icon="el-icon-switch-button"
                     @click="withdrawAuditStoreHandle(row.id)">
            撤销
          </el-button>
          <el-button type="text" icon="el-icon-delete" @click="deleteStoreHandle(row)" class="danger-color">
            删除
          </el-button>

        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :disabled="dataLoad"
        :current-page="searchForm.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="searchForm.limit"
        :total="totalNum"
        layout="total, sizes, prev, pager, next, jumper"
        class="paging">
    </el-pagination>
  </div>
</template>

<style scoped>
  .store-page .s-tool {
    margin-bottom: 7px;
  }
  .store-page .paging {
    text-align: right;
    margin: 7px;
  }
  .store-page .store-name {

  }
</style>
